package com.yoomiito.app.ui.order.sureorder.shopcar;

import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yoomiito.app.Constant;
import com.yoomiito.app.R;
import com.yoomiito.app.adapter.shopcar.ShopCarBuyAdapter;
import com.yoomiito.app.base.App;
import com.yoomiito.app.base.BaseActivity;
import com.yoomiito.app.model.bean.AddressInfo;
import com.yoomiito.app.model.my.MyRemainMoneyInfo;
import com.yoomiito.app.model.order.CreateOrderInfo;
import com.yoomiito.app.model.order.ShopCarGoods;
import com.yoomiito.app.ui.order.list.OrderActivity;
import com.yoomiito.app.ui.order.sureorder.BuyResultActivity;
import com.yoomiito.app.ui.order.UseCouponDialog;
import com.yoomiito.app.ui.anyview.order.ShowAddressView;
import com.yoomiito.app.ui.my.psw.SetPayPswActivity;
import com.yoomiito.app.ui.order.sureorder.singleGoods.BuyGoodsActivity;
import com.yoomiito.app.utils.encrypt.AESUtils;
import com.yoomiito.app.utils.AllCode;
import com.yoomiito.app.utils.AllUtils;
import com.yoomiito.app.utils.DensityUtil;
import com.yoomiito.app.utils.EventMessage;
import com.yoomiito.app.utils.L;
import com.yoomiito.app.utils.ResUtil;
import com.yoomiito.app.utils.SpannableUtils;
import com.yoomiito.app.utils.TouchUtils;
import com.yoomiito.app.utils.UserInfoConfig;
import com.yoomiito.app.utils.YMToast;
import com.yoomiito.app.widget.PasswordView_1;
import com.yoomiito.app.widget.SpacingDecoration;
import com.yoomiito.app.widget.TipDialog;
import com.yoomiito.app.widget.dialog.AlipayH5Dialog;
import com.yoomiito.app.widget.dialog.PayDialog;
import com.yoomiito.app.widget.dialog.PswInputDialog;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.droidlover.xdroidmvp.cache.SharedPref;

/**
 * 确认订单
 */
public class ShopCarBuyGoodsActivity extends BaseActivity<ShopCarBuyGoodsPresenter> {

    @BindView(R.id.act_buy_goods_money)
    TextView mPayPriceTv;
    @BindView(R.id.act_buy_goods_ll)
    LinearLayout parentView;
    @BindView(R.id.rcy)
    RecyclerView mRcy;

    private ArrayList<ShopCarGoods> mShopCarGoodsList;
    private AddressInfo mAddressInfo;
    public String mPayOrderId;
    public String mQueryOrderID;
    public String mPayMoney;//应付金额  来自于服务器
    public CreateOrderInfo mCreateOrderInfo;
    public int orderType;
    private int mGoodsType = AllCode.BaoPin;//目前只有爆品有购物车  则 商品都是爆品
    private int goodsSize = 1;
    private String eventId = "";
    private PayDialog payDialog;
    private String mGoodsTotalPrice = "0";//商品总额 显示用
    private String mBalance;//余额
    public String pay_type = "";//支付类型
    private PswInputDialog pswInputDialog;
    private ShowAddressView mShowAddressView;
    private ShopCarBuyAdapter buyAdapter;

    public static void start(Context context, ArrayList<ShopCarGoods> goodsDetails) {
        Intent intent = new Intent(context, ShopCarBuyGoodsActivity.class);
        intent.putParcelableArrayListExtra(Constant.KEY, goodsDetails);
//        intent.putExtra(Constant.TYPE,goodsType);
        context.startActivity(intent);
    }

    @Override
    public int getLayoutId() {
        return R.layout.act_buy_goods_shop_car_1;
    }

    @Override
    public ShopCarBuyGoodsPresenter newP() {
        return new ShopCarBuyGoodsPresenter(App.mAppConfig);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
//        AndroidBug5497Workaround.assistActivity(this);
//        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        mShopCarGoodsList = getIntent().getParcelableArrayListExtra(Constant.KEY);
//        mGoodsType = getIntent().getIntExtra(Constant.TYPE, 0);
        initView();
//        String ad = SharedPref.getInstance(this).getString(Constant.Address, "");
//        if (!TextUtils.isEmpty(ad)) {
//            mAddressInfo = JSON.parseObject(ad, AddressInfo.class);
//            mShowAddressView.setAddressInfo(mAddressInfo);
//            mShowAddressView.showAddress();
//        }
        int mTotalSize = 0;
        for (ShopCarGoods shopCarGoods : mShopCarGoodsList) {
            mGoodsTotalPrice = AllUtils.priceSum_2(mGoodsTotalPrice, AllUtils.priceMul(shopCarGoods.getSale_price(), shopCarGoods.getNum()));
            mTotalSize += shopCarGoods.getNum();
        }
        String s = "共" + mTotalSize + "件 合计¥" + mGoodsTotalPrice;
        int p = s.indexOf("¥");
        mPayPriceTv.setText(SpannableUtils.getSizeAndPriceText(s, R.color.color_ff5100, p, s.length(), p, p + 1));
        showLoading();
        getP().getAddress();
    }

    private void initView() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setStackFromEnd(true);
        mRcy.setLayoutManager(linearLayoutManager);
        mRcy.setItemAnimator(new DefaultItemAnimator());
        mRcy.addItemDecoration(new SpacingDecoration(0, DensityUtil.dp2px(10), false));
        buyAdapter = new ShopCarBuyAdapter(mShopCarGoodsList);
        mShowAddressView = new ShowAddressView(this);
        buyAdapter.addHeaderView(mShowAddressView);
        buyAdapter.bindToRecyclerView(mRcy);
        mRcy.scrollToPosition(0);//
    }

    @OnClick({R.id.act_buy_goods_btn, R.id.act_buy_goods_back})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.act_buy_goods_back:
                finish();
                break;
            case R.id.act_buy_goods_btn:
                if (AllUtils.isFastClick()) {
                    YMToast.showText("请勿重复点击");
                    return;
                }
                if (mAddressInfo == null) {
                    TouchUtils.onBuyEvent(eventId, UserInfoConfig.getRoleId(), UserInfoConfig.getAgent(), "empty_address");
                    showToast("请添加地址");
                    return;
                }
                showLoading();
                createOrder();
                //埋点
                break;


        }
    }

    public void showAddressView(AddressInfo addressInfo){
        dismissLoading();
        mAddressInfo = addressInfo;
        if (mAddressInfo!=null&&mAddressInfo.getId()!=null) {
            mShowAddressView.setAddressInfo(mAddressInfo);
            mShowAddressView.showAddress();
        }
    }

    //创建订单成功  通知购物车等 刷新数据
    public void createOrderSuccess() {
        EventMessage eventMessage = new EventMessage();
        eventMessage.setEventType(AllCode.NotifyShopCarData);
        EventBus.getDefault().postSticky(eventMessage);
        L.i("已通知刷新购物车数据");
    }

    //获取到微信结果后 查询订单状态

    @Override
    public void eventMessage(EventMessage eventMessage) {
        super.eventMessage(eventMessage);
        if (AllCode.BuyComplete.equals(eventMessage.getEventType())) {
            finish();
        } else if (Constant.PAY_RESULT.equals(eventMessage.getEventType())) {
            if (TextUtils.isEmpty(mQueryOrderID)) {
                showToast("订单状态异常");
                return;
            }
            showLoading();
            getP().queryOrder(mQueryOrderID, pay_type);
        }
    }


    //支付弹窗
    public void showPayDialog(MyRemainMoneyInfo data) {
        mBalance = data.getMoney();
        if (payDialog == null) {
            payDialog = new PayDialog(this);
            payDialog.setCanceledOnTouchOutside(false);
            payDialog.setOnResultListener((moneyPay, wxPay, aliPay,offline,quick, dismiss) -> {
                if (dismiss) {//取消支付
                    EventMessage eventMessage = new EventMessage();
                    eventMessage.setCode(AllCode.Fail);
                    payResult(eventMessage);
                    return;
                }
                if (moneyPay == 0 && wxPay == 0 && aliPay == 0) {
                    YMToast.showText("请选择付款通道");
                    return;
                }
                if(moneyPay == 1 && wxPay == 0 && aliPay == 0  && AllUtils.moneyCompare1(mGoodsTotalPrice,data.getMoney())){
                    YMToast.showText("您的余额不足够本次支付!");
                    return;
                }
                if (moneyPay == 1 && wxPay == 0 && aliPay == 0) {
                    //余额支付 需要密码框
                    if (UserInfoConfig.havePayPsw()) {
                        payDialog.dismiss();
                        showPsw();
                    } else {
                        showSetPswDialog();
                    }
                } else {
                    //非余额支付
                    showLoading();
                    getP().pay(mPayOrderId, wxPay, aliPay, moneyPay == 1 ? mBalance : "0", mCreateOrderInfo.getVip_order_type(), "");
                    payDialog.dismiss();
                }

            });
        }
        payDialog.setBalance(data.getMoney());
        payDialog.setPayMoney("¥" + mGoodsTotalPrice);
        payDialog.setRadio(AllUtils.moneyCompare(data.getMoney(), mGoodsTotalPrice));
        payDialog.show();
    }

    public void showSetPswDialog() {
        showSelectDialog(ResUtil.getString(R.string.my_tip),
                "为确保余额资金安全，请先设置千年艾支付密码"
                , "马上设置",
                "取消",
                new TipDialog.Dialogcallback() {
                    @Override
                    public void btnConfirm() {
                        SetPayPswActivity.start(ShopCarBuyGoodsActivity.this);
                    }

                    @Override
                    public boolean cancel() {
                        return false;
                    }
                });
    }

    private boolean show = false;
    public void setShow(){
        show = true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(show){
            findViewById(R.id.act_buy_goods_ll).post(new Runnable() {
                public void run() {
                    AlipayH5Dialog accountCancelDialog = new AlipayH5Dialog(ShopCarBuyGoodsActivity.this, new AlipayH5Dialog.OnCloseListener() {
                        @Override
                        public void confirm() {
//                            RouterUtils.toMain(BuyGoodsActivity.this, 4);
                            Intent intent = new Intent(ShopCarBuyGoodsActivity.this, OrderActivity.class);
                            intent.putExtra("type", 1);
                            startActivity(intent);
                            finish();

                        }
                    });
                    accountCancelDialog.show();
                }
            });
            show = false;
        }
    }
    //支付密码弹窗
    public void showPsw() {
        if (pswInputDialog == null) {
            pswInputDialog = new PswInputDialog(context);
            pswInputDialog.setTextChangedListener(new PasswordView_1.TextChangedListener() {
                @Override
                public void textChanged(CharSequence changeText) {

                }

                @Override
                public void textCompleted(CharSequence text) {//余额支付
                    showLoading();
                    getP().pay(mPayOrderId, 0, 0, mPayMoney, mCreateOrderInfo.getVip_order_type(), AESUtils.rsaEncrypt(text.toString()));
                }
            });
        }
        pswInputDialog.show();
    }

    private void createOrder() {
        List<ShopCarGoods> goodsList = buyAdapter.getData();
        JSONArray jsonArray = new JSONArray();
        for (ShopCarGoods goods : goodsList) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("product_id", goods.getProduct_id());
            jsonObject.put("note", TextUtils.isEmpty(goods.getNotes()) ? "" : goods.getNotes());
            jsonArray.add(jsonObject);
        }
        L.i("JSON; " + jsonArray.toJSONString());
        getP().createOrder(jsonArray.toJSONString(), mAddressInfo.getUserName(), mAddressInfo.getProvinceCode(),
                mAddressInfo.getCityCode(), mAddressInfo.getCountyCode(), mAddressInfo.getProvinceName() +
                        mAddressInfo.getCityName() + mAddressInfo.getCountyName(), mAddressInfo.getMobile(), mAddressInfo.getAddress());
    }

    public void error(boolean pswError, String tip) {
        if (pswInputDialog != null) {
            pswInputDialog.showErrorTip(pswError, tip);
        } else {
            YMToast.showText(tip);
            if (pswInputDialog != null) {
                pswInputDialog.dismiss();
            }
        }
    }

    //
    public void error(String tip) {
        YMToast.showText(tip);
        if (pswInputDialog != null) {
            pswInputDialog.dismiss();
        }
    }


    //根据订单状态 跳到支付结果
    public void payResult(EventMessage eventMessage) {
        dismissLoading();
        if ("wxpay".equals(pay_type)) {
            TouchUtils.onBuyEvent(eventId,
                    UserInfoConfig.getRoleId(),
                    UserInfoConfig.getAgent(),
                    AllCode.Fail == eventMessage.getCode() ? "wx_pay_fail" : "wx_pay_success");
        }
        eventMessage.setGoodsType(mGoodsType);
        eventMessage.setMsg(mPayOrderId);
        BuyResultActivity.Companion.start(ShopCarBuyGoodsActivity.this, eventMessage);
        finish();
    }

    private void showCouponDialog() {
        UseCouponDialog useCouponDialog = new UseCouponDialog(this);
        useCouponDialog.setOnSelectListener((position, isUseCoupon) -> {

        });
        useCouponDialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (AllCode.BuyAct == requestCode && data != null) {
            mAddressInfo = (AddressInfo) data.getSerializableExtra(Constant.DATA);
            mShowAddressView.setAddressInfo(mAddressInfo);
            mShowAddressView.showAddress();
            String addressJson = JSONObject.toJSON(mAddressInfo).toString();
            SharedPref.getInstance(this).putString(Constant.Address, addressJson);
        }
    }

    //点击EditText之外的区域隐藏键盘
    /*
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isSoftShowing() && isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                    return true;
                }
            }
        }
        return super.dispatchTouchEvent(ev);
    }
    */

    //判断软键盘是否正在展示
    private boolean isSoftShowing() {
        //获取当前屏幕内容的高度
        int screenHeight = getWindow().getDecorView().getHeight();
        //获取View可见区域的bottom
        Rect rect = new Rect();
        getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);

        return screenHeight - rect.bottom != 0;
    }


    //是否需要隐藏键盘
    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

}
